package io.gitee.zhangbinhub.acp.core.file

import io.gitee.zhangbinhub.acp.core.common.CalendarTools
import io.gitee.zhangbinhub.acp.core.common.CommonTools.doDeleteFile
import io.gitee.zhangbinhub.acp.core.common.CommonTools.getWebRootAbsPath
import io.gitee.zhangbinhub.acp.core.common.CommonTools.isNullStr
import io.gitee.zhangbinhub.acp.core.common.log.LogFactory.Companion.getInstance
import org.bouncycastle.util.encoders.Hex
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object FileOperation {
    private val log = getInstance(FileOperation::class.java)

    @JvmStatic
    fun generateNowTimeString(): String {
        return CalendarTools.getDateTimeString(null, "yyyyMMddHHmmssSSS")
    }

    /**
     * 获取文件基路径
     *
     * @param filePath 文件绝对路径
     * @return 基路径
     */
    @JvmStatic
    fun getFileBaseURL(filePath: String?): String? {
        var path = filePath
        return try {
            if (isNullStr(path)) {
                path = getWebRootAbsPath()
            }
            File(path!!).toURI().toURL().toString()
        } catch (e: Exception) {
            log.error("Get file baseURL is failed")
            null
        }
    }

    /**
     * 十六进制制字符串转图片文件
     *
     * @param hexString      十六进字符串
     * @param fileName       文件名
     * @param extensionsName 扩展名
     * @param pathFlag       生成图片文件路径标志:0-相对于WebRoot；1-自定义
     * @param resultPathFlag 返回文件路径标志:0-相对于WebRoot；1-绝对路径
     * @param parentPath     生成图片所在目录
     * @param isDelete       是否异步删除临时图片
     * @return 临时图片路径
     */
    fun hexToImage(
        hexString: String,
        fileName: String,
        extensionsName: String,
        pathFlag: Int,
        resultPathFlag: Int,
        parentPath: String,
        isDelete: Boolean
    ): String {
        var fileAbsPath: String
        var tmpFile: File? = null
        var out: FileOutputStream? = null
        val webRootAbsPath = getWebRootAbsPath()
        try {
            tmpFile = if (pathFlag == 0) {
                File(webRootAbsPath + File.separator + "files" + File.separator + "tmp" + File.separator + fileName + "." + extensionsName)
            } else {
                File(parentPath + File.separator + fileName + "." + extensionsName)
            }
            val bytes = Hex.decode(hexString)
            out = FileOutputStream(tmpFile)
            out.write(bytes)
            out.flush()
            out.close()
            fileAbsPath = if (resultPathFlag == 0) {
                tmpFile.getCanonicalPath().replace(webRootAbsPath, "").replace(File.separator, "/")
            } else {
                tmpFile.getCanonicalPath().replace(File.separator, "/")
            }
            if (isDelete) {
                doDeleteFile(tmpFile, true)
            }
        } catch (e: Exception) {
            log.error("generate image failed:" + e.message, e)
            try {
                out?.close()
            } catch (e1: IOException) {
                log.error(e1.message, e1)
            } finally {
                if (tmpFile != null) {
                    doDeleteFile(tmpFile, false)
                }
            }
            fileAbsPath = ""
        }
        return fileAbsPath
    }

    /**
     * 生成临时文件夹
     *
     * @return 临时文件夹绝对路径
     */
    fun buildTempDir(): String {
        val webRootAdsPath = getWebRootAbsPath()
        val file = File(
            webRootAdsPath + File.separator + "files" + File.separator + "tmp"
        )
        if (!file.exists()) {
            if (!file.mkdirs()) {
                log.error("mkdir failed : " + file.getCanonicalPath())
            }
        }
        return file.getCanonicalPath()
    }

    /**
     * 获取模板文件夹
     *
     * @return 模板文件夹绝对路径
     */
    @JvmStatic
    fun buildTemplateDir(): String {
        val webRootAdsPath = getWebRootAbsPath()
        val file = File(
            webRootAdsPath + File.separator + "files" + File.separator + "template"
        )
        if (!file.exists()) {
            if (!file.mkdirs()) {
                log.error("mkdir failed : " + file.getCanonicalPath())
            }
        }
        return file.getCanonicalPath()
    }
}
